package top.huiwow.commands;


import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import top.huiwow.GameCore;
import top.huiwow.entity.EntityManager;

import java.util.ArrayList;
import java.util.List;

public class SpawnEntityCommand implements CommandExecutor, TabCompleter {

    private final EntityManager entityManager;

    public SpawnEntityCommand() {
        entityManager = GameCore.getInstance().getEntityManager();
    }

    @Override
    public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
        if (sender instanceof Player) {
            Player player = ((Player) sender);
            Location location = player.getEyeLocation();
            if (args.length == 2) {
                int id;
                int level;
                try {
                    id = Integer.parseInt(args[0]);
                } catch (NumberFormatException e) {
                    sender.sendMessage("NAN");
                    return true;
                }
                try {
                    level = Integer.parseInt(args[1]);
                } catch (NumberFormatException e) {
                    sender.sendMessage("NAN");
                    return true;
                }
                entityManager.spawnEntity(location, id, level);
            } else {
                sender.sendMessage("correct usage:/spawnakaishi <id> <level>");
            }
        }

        return true;
    }

    @Override
    public List<String> onTabComplete(CommandSender sender, Command cmd, String label, String[] args) {
        if (args.length != 1) return null;

        List<String> groupnames = new ArrayList<>();
        groupnames.add("0");
        String arg = args[0];

        if (!isEmptyTab(arg)) {
            return autofill(groupnames, arg);
        }

        return groupnames;
    }

    private boolean isEmptyTab(String s) {
        return s == null || s.equals(" ") || s.isEmpty();
    }

    private List<String> autofill(List<String> groupnames, String input) {
        List<String> list = new ArrayList<>();

        for (String entry : groupnames) {
            if (entry.length() >= input.length()) {
                if (input.equalsIgnoreCase(entry.substring(0, input.length()))) {
                    list.add(entry);
                }
            }
        }

        if (list.isEmpty()) {
            return groupnames;
        }

        return list;
    }
}
